import React, { useEffect, useState } from 'react';
import { Table, Button, Input, Popconfirm, message, Modal, Form, Select, DatePicker } from 'antd';
import { get, post, put, delete as del } from '../../../components/axios';
import dayjs from 'dayjs';



export default function SubcontractSuppliers() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editRecord, setEditRecord] = useState(null); // 当前编辑的记录

  const columns = [
    { title: 'ID', dataIndex: '_id', key: '_id', width: 60, render: (t, r, i) => i + 1 },
    {
      title: '状态', dataIndex: 'status', key: 'status', render: v => {
        if (v === '已完成') return <span style={{ color: 'blue' }}>{v}</span>;
        if (v === '进行中') return <span style={{ color: 'orange' }}>{v}</span>;
        if (v === '已暂停') return <span style={{ color: 'red' }}>{v}</span>;
        return v;
      }
    },
    { title: '进度', dataIndex: 'progress', key: 'progress' },
    { title: '需求描述', dataIndex: 'desc', key: 'desc' },
    { title: '提出人', dataIndex: 'proposer', key: 'proposer' },
    { title: '负责人', dataIndex: 'owner', key: 'owner' },
    { title: '任务开始时间', dataIndex: 'startDate', key: 'startDate', render: v => v ? dayjs(v).format('YYYY-MM-DD') : '' },
    { title: '任务结束时间', dataIndex: 'endDate', key: 'endDate', render: v => v ? dayjs(v).format('YYYY-MM-DD') : '' },
    { title: '工期天数', dataIndex: 'planDays', key: 'planDays', render: v => v ? `${v}天` : '' },
    { title: '工期工时', dataIndex: 'planHours', key: 'planHours', render: v => v ? `${v}h` : '' },
    { title: '实际完结时间', dataIndex: 'actualEnd', key: 'actualEnd', render: v => v ? dayjs(v).format('YYYY-MM-DD') : '' },
    { title: '实际工期天数', dataIndex: 'actualDays', key: 'actualDays', render: v => v ? `${v}天` : '' },
    { title: '实际工时', dataIndex: 'actualHours', key: 'actualHours', render: v => v ? `${v}h` : '' },
    { title: '任务成本', dataIndex: 'cost', key: 'cost', render: v => v ? `¥${v}` : '' },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime', render: v => v ? dayjs(v).format('YYYY-MM-DD') : '' },
    { title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', render: v => v ? dayjs(v).format('YYYY-MM-DD') : '' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          <Button size="small" onClick={() => onEdit(record)}>编辑</Button>
          <Button size="small" danger style={{ marginLeft: 8 }} onClick={() => onDelete(record._id)}>删除</Button>

        </>
      ),
    },
  ];

  const fetchData = async (page = 1, pageSize = 10, searchVal = '') => {
    setLoading(true);
    const res = await get('/api/SubcontractSuppliers/list', { page, pageSize, search: searchVal });
    setData(res.data.data);
    setPagination({ current: page, pageSize, total: res.data.total });
    setLoading(false);
  };

  useEffect(() => {
    fetchData();
  }, []);

  const onDelete = async (_id) => {
    
    await del('/api/SubcontractSuppliers/delete', { _id });
    message.success('删除成功');
    fetchData(pagination.current, pagination.pageSize, search);
  };

  const onEdit = (record) => {
    setEditRecord(record);
    form.setFieldsValue({
      ...record,
      // 日期字段需转为 dayjs 对象
      startDate: record.startDate ? dayjs(record.startDate) : null,
      endDate: record.endDate ? dayjs(record.endDate) : null,
      actualEnd: record.actualEnd ? dayjs(record.actualEnd) : null,
      createTime: record.createTime ? dayjs(record.createTime) : null,
      updateTime: record.updateTime ? dayjs(record.updateTime) : null,
    });
    setModalVisible(true);
  };

  const onAdd = () => {
    form.resetFields();
    setModalVisible(true);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      // 日期转字符串
      ['startDate', 'endDate', 'actualEnd', 'createTime', 'updateTime'].forEach(key => {
        if (values[key]) values[key] = values[key].format('YYYY-MM-DD');
      });
      if (editRecord) {
        // 编辑
        await put('/api/SubcontractSuppliers/update', { ...values, id: editRecord._id });
        message.success('编辑成功');
      } else {
        // 新增
        await post('/api/SubcontractSuppliers/add', values);
        message.success('添加成功');
      }
      setModalVisible(false);
      setEditRecord(null);
      fetchData(1, pagination.pageSize, search);
    } catch (e) {
      // 校验失败或请求失败
      
    }
  };

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" onClick={onAdd}>添加</Button>
        <Input.Search
          placeholder="搜索"
          style={{ width: 200, marginLeft: 8 }}
          onSearch={val => { setSearch(val); fetchData(1, pagination.pageSize, val); }}
          allowClear
        />
      </div>
      <Table
        rowKey="_id"
        columns={columns}
        dataSource={data}
        loading={loading}
        pagination={{
          ...pagination,
          onChange: (page, pageSize) => fetchData(page, pageSize, search),
        }}
      />

      <Modal
        title="添加需求"
        visible={modalVisible}
        onOk={handleOk}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item name="status" label="状态" rules={[{ required: true }]}>
            <Select>
              <Select.Option value="已完成">已完成</Select.Option>
              <Select.Option value="进行中">进行中</Select.Option>
              <Select.Option value="已暂停">已暂停</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="progress" label="进度" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="desc" label="需求描述" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="proposer" label="提出人" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="owner" label="负责人" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="startDate" label="任务开始时间">
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="endDate" label="任务结束时间">
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="planDays" label="工期天数">
            <Input />
          </Form.Item>
          <Form.Item name="planHours" label="工期工时">
            <Input />
          </Form.Item>
          <Form.Item name="actualEnd" label="实际完结时间">
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="actualDays" label="实际工期天数">
            <Input />
          </Form.Item>
          <Form.Item name="actualHours" label="实际工时">
            <Input />
          </Form.Item>
          <Form.Item name="cost" label="任务成本">
            <Input />
          </Form.Item>
          <Form.Item name="createTime" label="创建时间">
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="updateTime" label="更新时间">
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
